package com.bianguo.android.tencentpushdemo.view.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsListView;
import android.widget.LinearLayout;

import com.bianguo.android.tencentpushdemo.R;
import com.bianguo.android.tencentpushdemo.adapters.CommentAdapter;
import com.bianguo.android.tencentpushdemo.adapters.CommentListAdapter;
import com.bianguo.android.tencentpushdemo.utils.MyLog;
import com.bianguo.android.tencentpushdemo.utils.PermissionHelper;
import com.bianguo.android.tencentpushdemo.view.widget.DetailListView;
import com.bianguo.android.tencentpushdemo.view.widget.DetailScrollView;

import net.ypresto.androidtranscoder.MediaTranscoder;
import net.ypresto.androidtranscoder.format.MediaFormatStrategy;
import net.ypresto.androidtranscoder.format.MediaFormatStrategyPresets;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class NewsDetailActivity extends BaseActivity implements AppBarLayout.OnOffsetChangedListener, AbsListView.OnScrollListener {

    @BindView(R.id.news_detail_web)
    WebView detailWeb;
    @BindView(R.id.news_detail_list)
    RecyclerView commentRv;
    @BindView(R.id.news_detail_toolbar)
    Toolbar mToolbar;

    //    public final String NEWS_DETAIL_BASE_URL = "http://demo.bianguo.com.cn/zhuzhenyu/scnews/index.php/Home/Index/news?Nid=12";
    public final String NEWS_DETAIL_BASE_URL = "https://wx.zjsfgkw.cn/Api/index.php/home/news/Newsdetail?zybm=1300B00160002141&aid=187889&ncataid=402&t=1529572808";
    public final String VIDEO_PATH = "/storage/emulated/0/DCIM/Camera/VID_20170519_170341.mp4";
    private WebSettings webSettings;
    private ArrayList<String> comments;
    private BottomSheetDialog mBottomSheetDialog;
    private CommentListAdapter adapter;
    private CommentAdapter commentAdapter;
    private int mListScrollState = AbsListView.OnScrollListener.SCROLL_STATE_IDLE;
    private int mFirstVisibleItem;
    private int mWebViewHeight;
    private int mScreenHeight;
    private int mLastY;

    @Override
    public int layoutId() {
        return R.layout.activity_news_detail;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        webSettings = detailWeb.getSettings();
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存
        //解决htts在5.0以上不能显示图片问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        detailWeb.loadUrl(NEWS_DETAIL_BASE_URL);
        detailWeb.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(final WebView view, String url) {
                super.onPageFinished(view, url);
                int w = View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED);
                int h = View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED);
                //重新测量
                //view.measure(w, h);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mWebViewHeight = view.getHeight();
                    }
                }, 100);
            }
        });

        detailWeb.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                WebView.HitTestResult hitTestResult = detailWeb.getHitTestResult();
                String url = hitTestResult.getExtra();
                int type = hitTestResult.getType();
                MyLog.myLog("url = " + url + ", type = " + type);
                if (WebView.HitTestResult.IMAGE_TYPE == type ||
                        WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
                    MyLog.myLog("images --------");
                }
                return true;
            }
        });
        comments = new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            comments.add("我有一只小蚂蚁我从来都不起，有一天我心血来潮带她去赶集，啦啦啦啦啦啦啦啦啦啦 " + i);
        }
        commentAdapter = new CommentAdapter(mContext, comments);
        commentRv.setAdapter(commentAdapter);
        commentRv.setNestedScrollingEnabled(false);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("详情");
    }

    private void setBehaviorCallback() {
        View view = mBottomSheetDialog.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet);
        final BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(view);
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    mBottomSheetDialog.dismiss();
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            }
        });
    }

    @Override
    public void initData() {
//        boolean permission = PermissionHelper.getInstance(mContext).isPermission(mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
//        MyLog.myLog("permission = " + permission);
//        if (permission) {
//            loadLocalVideo();
//            compressVideo(VIDEO_PATH);
//        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 0:
                if (PackageManager.PERMISSION_GRANTED == grantResults[0]) {
                    MyLog.myLog("权限申请成功");
                    loadLocalVideo();
                } else {
                    MyLog.myLog("没有该该权限");
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }

    private void compressVideo(String videoPath) {
        try {
            File dirFile = new File(Environment.getExternalStorageDirectory() + "/tempVideo/");
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            File videoFile = new File(dirFile, System.currentTimeMillis() + ".mp4");
            MyLog.myLog("videoFile.getAbsolutePath() = " + videoFile.getAbsolutePath());
            MediaTranscoder.getInstance().transcodeVideo(videoPath, videoFile.getAbsolutePath(), MediaFormatStrategyPresets.createAndroid720pStrategy(1024 * 1204 * 2), new MediaTranscoder.Listener() {
                @Override
                public void onTranscodeProgress(double progress) {

                }

                @Override
                public void onTranscodeCompleted() {
                    MyLog.myLog("completed");
                }

                @Override
                public void onTranscodeCanceled() {
                    MyLog.myLog("canceled");
                }

                @Override
                public void onTranscodeFailed(Exception exception) {
                    MyLog.myLog("failed");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void loadLocalVideo() {
        final String[] columns = {MediaStore.Images.Media.DATA,
                MediaStore.Images.Media._ID};
        final String orderBy = MediaStore.Images.Media.DATE_TAKEN;

        Cursor videoCursor = this
                .getApplicationContext()
                .getContentResolver()
                .query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns,
                        null, null, orderBy + " DESC");
        for (int i = 0; i < videoCursor.getCount(); i++) {
            videoCursor.moveToPosition(i);
            int dataColumnIndex = videoCursor
                    .getColumnIndex(MediaStore.Video.Media.DATA);
            String videoUrl = videoCursor.getString(dataColumnIndex);
            MyLog.myLog("videoUrl = " + videoUrl);
        }
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (0 == verticalOffset) {
            //展开状态
        } else if (appBarLayout.getTotalScrollRange() == Math.abs(verticalOffset)) {
            //折叠状态
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        mListScrollState = scrollState;
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        mFirstVisibleItem = firstVisibleItem;
    }
}
